<?php

function win_observation_advanced_search() {
  return win_observation_advanced_search_ui();
}

function win_observation_advanced_search_ui() {
  $path = drupal_get_path('module','win_observation');
  drupal_add_js($path . '/js/functions.js');
  drupal_add_js($path . '/js/search/win_observation_advanced_search.js');
  drupal_add_js($path . '/js/external/jquery-1.3.2.js');
  drupal_add_js($path . '/js/external/jquery.dataTables.js');
  drupal_add_js($path . '/js/search_results_page.js');

  drupal_add_css($path . '/css/jquery-ui.css');
  drupal_add_css($path . '/css/jquery.datatable/css/demo_table.css');
  drupal_add_css($path . '/css/win_observation_advanced_search.css');

  $html = '';

  $col_names = array();
  $col_names['s_kingdom'] = t('Kingdom');
  $col_names['s_phylum'] = t('Phylum');
  $col_names['s_class'] = t('Class');
  $col_names['s_order'] = t('Order');
  $col_names['s_family'] = t('Family');
  $col_names['s_genus'] = t('Genus');
  $col_names['s_species'] = t('Species');
  $col_names['s_scientific_name'] = t('Scientific Name');
  // $col_names['gender'] = t('Gender');
  // $col_names['lifestage'] = t('Life Stage');
  $col_names['waterbody_type'] = t('Waterbody Type');
  $col_names['waterbody_name'] = t('Waterbody Name');
  // $col_names['comments'] = t('Comments');
  $col_names['record_language'] = t('Record Language');
  $col_names['country'] = t('Country');
  $col_names['region'] = t('Region/ State/ County');
  $col_names['district'] = t('Disctrict');
  $col_names['city'] = t('City');
  $col_names['locality'] = t('Locality');
  $col_names['fname'] = t('Observer - First Name');
  $col_names['lname'] = t('Observer - Last Name');
  $col_names['affiliation'] = t('Observer - Affiliation');
  //  $col_names['address'] = t('Observer - Address');
  //  $col_names['email'] = t('Observer - Email');

  $comparision_options = array();
  $comparision_options['is'] = 'is';
  $comparision_options['starts_with'] = 'starts with';
  $comparision_options['contains'] = 'contains';
  $comparision_options['ends_with'] = 'ends with';
  $comparision_options['not_is'] = 'not is';
  $comparision_options['not_starts_with'] = 'not starts with';
  $comparision_options['not_contains'] = 'not contains';
  $comparision_options['not_ends_with'] = 'not ends with';

  $conjunction_types = array();
  $conjunction_types['.'] = '';
  $conjunction_types['and'] = 'and';
  $conjunction_types['or'] = 'or';
  $conjunction_types['and_('] = 'and (';
  $conjunction_types['or_('] = 'or (';
  $conjunction_types[')'] = ')';
  $conjunction_types[')_and'] = ') and';
  $conjunction_types[')_or'] = ') or';
  $conjunction_types[')_and_('] = ') and (';
  $conjunction_types[')_or_('] = ') or (';

  $html = <<<EOT
  <div style="text-align:center">
    <div id="divSearchUI">
      <div id="divSearchContainer" class="container-inline">
        <select name="col">
EOT;
  $html .= createDropDownOptionsHTML($col_names);
  $html .= <<<EOT
        </select>
        <select name="compOpt">
EOT;
  $html .= createDropDownOptionsHTML($comparision_options);
  $html .= <<<EOT
        </select>
        <input type="textbox" size="20" name="txtKeyword"/>
        <select name="conjunc">
EOT;
  $html .= createDropDownOptionsHTML($conjunction_types);
  $html .= <<<EOT
        </select>
      </div>
      <div id="divSearchUIPlaceholder">
      </div>
    </div>
    <input type="button" id="btnSearch" value="Search" />
    <div id="divAdvancedSearchResults"></div>
  </div>
EOT;
  return $html;
}

function createDropDownOptionsHTML($arr_options) {
  $options = '';

  foreach ($arr_options as $id => $name) {
    $options .= '<option value="'.$id.'">'.t($name).'</option>';
  }

  return $options;
}

function perform_advanced_search($params) {
  $conds = $params['conditions'];

  if (!is_array($conds) || count($conds) == 0) {
    die(json_encode(set_error_arr("Required parameters missing.")));
  }

  $len = count($conds);
  $query_where = array();
  for ($i = 0; $i < $len; $i++) {
    $cond = $conds[$i];
    $where = array();
    $where[] = 'lower('.$cond['col'].')';
    //_escape_accidental_placeholders_from_Drupal(db_escape_string($srchStr));
    $keyword = strtolower(db_escape_string($cond['keyword']));
    $drupal_escaped_keyword = _escape_accidental_placeholders_from_Drupal($keyword);
    switch ($cond['opt']) {
      case 'is':
        $where[] = "= '" . $keyword . "'";
        break;
      case 'starts_with':
        $where[] = "like '" . $keyword . "%'";
        break;
      case 'contains':
        $where[] = "like '%" . $drupal_escaped_keyword . "%'";
        break;
      case 'ends_with':
        $where[] = "like '%" . $drupal_escaped_keyword . "'";
        break;
      case 'not_is':
        $where[] = "!= '" . $keyword . "'";
        break;
      case 'not_starts_with':
        $where[] = "not like '" . $keyword . "%'";
        break;
      case 'not_contains':
        $where[] = "not like '%" . $drupal_escaped_keyword . "%'";
        break;
      case 'not_ends_with':
        $where[] = "not like '%" . $drupal_escaped_keyword . "'";
        break;
    }
    if ($cond['conjunc'] != '.') {
      $where[] = str_replace('_', ' ', $cond['conjunc']);
    }
    $query_where[$i] = implode(' ', $where);
  }

  $sql_filter_unvalidated = " and id in (select observation_id from win_validation where status = 1)";
  $oids = array();
  $query = "select id from win_observation_textual_data_view where (" . implode(' ', $query_where) . ") {$sql_filter_unvalidated};";
  $result = db_query($query);
  if (!$result) {
    return FALSE;
  } else {
    while ($obj = db_fetch_object($result)) {
      $oids[] = $obj->id;
    }
  }

  $observations = get_observation_info_for_search_results($oids);
  $output = show_search_results($observations);
  $output .= show_download_UI();

  $response = set_no_error_arr("");
  $response['result'] = $output;

  die(json_encode($response));
}

function show_download_UI() {
  $base_path = base_path();
  
  $html = <<<EOT
  <div style="text-align: left;">
    <div style="font-weight: bold; font-size: 15px;">Download search results</div>
    <div style="width:100%; text-align: center;">
      We are currently working on this feature. This feature will allow you to download the search results in XLS and CSV formats.
      <img alt="Work in Progress" src="{$base_path}sites/default/files/work_in_progress.png" />
    </div>
  </div>
EOT;
  
  return $html;
}